package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdongshop.constant.OssConstant;
import com.dongdongshop.data.HttpResponseEnum;
import com.dongdongshop.data.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@RequestMapping("imageController")
public class ImageController {

    private final Logger logger= LoggerFactory.getLogger(ImageController.class);

    @RequestMapping("upLoadFile")
    @ResponseBody
    public Result upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile) {
        try{
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = OssConstant.ENDPOINT;
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = OssConstant.ACCESSKEYID;
            String accessKeySecret = OssConstant.ACCESSKEYSECRET;
            String bucketName = OssConstant.BUCKETNAME;
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = myFile.getOriginalFilename();//上传文件的路径

// 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            //String content = "Hello OSS";
            String url = null;//前台路径
            try {
                ossClient.putObject(bucketName, objectName, myFile.getInputStream());
                //拼接图片访问路径
                url = "http://" + bucketName + OssConstant.POINT+ objectName;

            } catch (IOException e) {
                e.printStackTrace();
                return Result.jsonResponse(HttpResponseEnum.FAIL);
            }

// 关闭OSSClient。
            ossClient.shutdown();
            return Result.jsonResponse(HttpResponseEnum.OK).setData(url);
        }catch (Exception e){
            logger.info("操作异常",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }

}
